import React from 'react';
import {connect} from 'react-redux';
import {Link} from 'react-router-dom';
class List extends React.Component{
  constructor(props){
    super(props);
    this.idRef=React.createRef();
    this.nameRef=React.createRef();
    this.priceRef=React.createRef();
  }

  addList(){
      let list={
          id:this.idRef.current.value,
          name:this.nameRef.current.value,
          price:this.priceRef.current.value,
      }
    //   console.log(list)
    this.idRef.current.value = '';
    this.nameRef.current.value = '';
    this.priceRef.current.value = '';
    this.props.addList(list)
  }

  render(){
 let lists=this.props.lists;
//  console.log(lists)
    return(
      <div>
          id:<input type='text' ref={this.idRef}/>
          name:<input type='text' ref={this.nameRef}/>
          price:<input type='text' ref={this.priceRef}/>
          <button onClick={e=>this.addList()} style={{marginLeft:'10px'}}>添加商品</button>
         <ul>
             {
                lists.map((item)=>{
                     return(
                         <li key={item.id}>
                             产品名称：{item.name}
                             价格：{item.price}
                             <button onClick={e=>this.props.addShoppingCar(item)}>加入购物车</button>
                         </li>
                         
                     )
                 })
             }
         </ul>
         <div className='shopingCar'>
           <Link to='/shoppingcar'>购物车({this.props.itemCount()})</Link>
         </div>
      </div>
    )
  }
}

function mapStateToProps(state){
    console.log(state)
    return{
        lists:state.lists.lists,
        itemCount(){
            return state.shoppingCar.items.reduce(function(preValue,item){
                return preValue+item.count
            },0)
        }

    }
}

function postAddList(list){
    return new Promise((resolve,reject)=>{
        setTimeout(function(){
            resolve({...list,id:'010'})
        },1000)
    })
};

function postShoppingCar(item){
    return new Promise((resolve,reject)=>{
        setTimeout(function(){
            resolve({...item,id:item.id})
        },1000)
    })
}

function mapDispatchToProps(dispatch){
    return{
        async addShoppingCar(item){
           await dispatch(async(dispatch)=>{
                let result=await postShoppingCar(item);
                dispatch({type:'ADD_LISTS',item:result})
            })
        },
        async addList(list){
            await dispatch(async (dispatch)=>{
                let result=await postAddList(list);
                dispatch({type:'ADD_GOODS',list:result})
            })
        }
    }
}

export default connect(mapStateToProps,mapDispatchToProps)(List);
